/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.ins.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.ins.entity.InsField;
import com.thinkgem.jeesite.modules.ins.entity.InsTable;
import com.thinkgem.jeesite.modules.ins.entity.InsTableTemplate;
import com.thinkgem.jeesite.modules.ins.dao.InsFieldDao;
import com.thinkgem.jeesite.modules.ins.dao.InsTableTemplateDao;

/**
 * 数据表模板Service
 * @author fanqinglong
 * @version 2018-05-30
 */
@Service
@Transactional(readOnly = true)
public class InsTableTemplateService extends CrudService<InsTableTemplateDao, InsTableTemplate> {
	@Autowired
	private InsFieldDao insFieldDao;
	
	public InsTableTemplate get(String id) {
		InsTableTemplate insTableTemplate = super.get(id);
		insTableTemplate.setInsFieldList(insFieldDao.findList(new InsField(new InsTable(id))));
		return insTableTemplate;
	}
	
	public List<InsTableTemplate> findList(InsTableTemplate insTableTemplate) {
		return super.findList(insTableTemplate);
	}
	
	public Page<InsTableTemplate> findPage(Page<InsTableTemplate> page, InsTableTemplate insTableTemplate) {
		return super.findPage(page, insTableTemplate);
	}
	
	public InsTableTemplate getByName(InsTableTemplate insTableTemplate){
		return dao.getByName(insTableTemplate);
	}
	
	@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false, rollbackFor = Exception.class)
	public void save(InsTableTemplate insTableTemplate) {
		super.save(insTableTemplate);
		for (InsField insField : insTableTemplate.getInsFieldList()){
			if (insField.getId() == null){
				continue;
			}
			if (InsField.DEL_FLAG_NORMAL.equals(insField.getDelFlag())){
				insField.setPreValues(StringUtils.replaceHTMLentity(insField.getPreValues()));
				if (StringUtils.isBlank(insField.getId())){
					insField.setTable(new InsTable(insTableTemplate.getId()));
					insField.preInsert();
					insField.setFrequently("0");
					insFieldDao.insert(insField);
				}else{
					insField.preUpdate();
					insFieldDao.update(insField);
				}
			}else{
				insFieldDao.delete(insField);
			}
		}
	}
	
	@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false, rollbackFor = Exception.class)
	public void delete(InsTableTemplate insTableTemplate) {
		super.delete(insTableTemplate);
	}
	
}